package com.jzwl.site.wap.site.controller;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jzwl.common.constant.AjaxStatusConstant;
import com.jzwl.common.constant.Constants;
import com.jzwl.common.page.PageObject;
import com.jzwl.common.utils.HttpClientUtil;
import com.jzwl.site.manager.company.service.SiteCompanyService;
import com.jzwl.site.wap.index.service.WebService;
import com.jzwl.system.base.controller.BaseController;

@Controller
@RequestMapping("/site/web")
public class SiteWebController extends BaseController {

	@Autowired
	private WebService webService;

	@Autowired
	private Constants constants;

	@Autowired
	private SiteCompanyService siteCompanyService;

	private static Logger log = LoggerFactory.getLogger(SiteWebController.class);

	@RequestMapping(value = "/index")
	public ModelAndView articleIndex(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mov = new ModelAndView();
		createParameterMap(request);
		//加载顶部menu动态部分
		List<Map<String, Object>> mlist = webService.queryFirstMenu();
		mov.addObject("mlist", mlist);

		///加载置顶栏目信息
		Map<String, Object> nodemap = webService.queryTopNode();
		mov.addObject("tnode", nodemap);

		///加载新闻动态信息dxf
		Map<String, Object> nodemapCreaTime = webService.queryTopNodeCreaTime();
		List<Map<String, Object>> list = (List<Map<String, Object>>) nodemapCreaTime.get("arlist");
		for (int i = 0; i < list.size(); i++) {
			String st = String.valueOf(list.get(i).get("content"));
			Document parse = Jsoup.parse(st);
			String str = parse.html();
			String reg = "[^\u4e00-\u9fa5]";
			str = str.replaceAll(reg, "");
			str = str.replaceAll("微软雅黑", "");
			list.get(i).put("content", str);
			String createTime = String.valueOf(list.get(i).get("pubTime"));
			String ymd = createTime.substring(0, 11);
			String[] split = ymd.split("-");
			String day = split[2];
			String moth = checkMoth(split[1]);
			list.get(i).put("day", day);
			list.get(i).put("moth", moth);
		}

		mov.addObject("NomeTnode", nodemapCreaTime);

		///加载轮播图信息
		//		List<Map<String, Object>> alist = webService.queryTopArticle();
		//		mov.addObject("alist",alist);

		///加载首页栏目信息
		List<Map<String, Object>> tlist = webService.queryTopNodeInfo();
		mov.addObject("tlist", tlist);
		//加载专题信息
		List<Map<String, Object>> slist = webService.queryStaticInfo("1");
		mov.addObject("slist", slist);

		//加载合作伙伴信息
		List<Map<String, Object>> plist = webService.queryStaticInfo("2");
		mov.addObject("plist", plist);

		//加载图片服务器地址
		mov.addObject("staticpath", constants.getSftz_online_path());
		mov.setViewName("/wap/site/index");
		return mov;
	}

	@RequestMapping(value = "/{nodeid}")
	public ModelAndView nodeList(@PathVariable String nodeid, HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		ModelAndView mov = loadMenuInfo(nodeid);

		///获取当前栏目文章列表
		PageObject po = new PageObject();
		try {
			Map<String, Object> currmap = (Map<String, Object>) mov.getModel().get("currentNode");
			paramsMap.put("isDelete", 0);
			if (currmap != null) {
				paramsMap.put("nodeId", currmap.get("id"));
			}

			//			paramsMap.put("limit", 2);///测试使用

			po = webService.queryArticleList(paramsMap);
			List<Map<String, Object>> listData = po.getDatasource();
			if (listData.size() == 1) {//当栏目下只有一个的时候，直接进入详情页面
				mov.setViewName("redirect:/web/" + listData.get(0).get("nodeId") + "/"
						+ listData.get(0).get("articleId") + ".html");
				return mov;
			}
			//			po.setPageSize(2);

			mov.addObject("totalProperty", po.getTotalCount());
			mov.addObject("page", po);
			mov.addObject("tarId", nodeid);
			mov.setViewName("/wap/list");
		} catch (Exception e) {

			e.printStackTrace();
			mov.addObject("msg", "Article列表查询失败");
			mov.setViewName("/error");
		}
		return mov;
	}

	@RequestMapping(value = "/{nodeid}/{articleid}")
	public ModelAndView articleDetail(@PathVariable String nodeid, @PathVariable String articleid,
			HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		ModelAndView mov = loadMenuInfo(nodeid);

		Map amap = webService.queryArticleById(articleid);
		mov.addObject("article", amap);
		mov.setViewName("/wap/article");
		return mov;
	}

	@RequestMapping(value = "/us")
	public ModelAndView us(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		ModelAndView mov = new ModelAndView();
		//加载顶部menu动态部分
		List<Map<String, Object>> mlist = webService.queryFirstMenu();
		mov.addObject("mlist", mlist);

		Map usmap = webService.queryUsInfo();
		mov.addObject("usobj", usmap);
		mov.addObject("us", 1);
		mov.setViewName("/wap/us");
		return mov;
	}

	protected ModelAndView loadMenuInfo(String nodeid) {
		ModelAndView mov = new ModelAndView();

		//加载顶部menu动态部分
		List<Map<String, Object>> mlist = webService.queryFirstMenu();
		mov.addObject("mlist", mlist);
		//当前栏目Id
		Map currentNode = null;
		Map currentMenu;
		//获取当前栏目信息
		Map cnmap = webService.queryNodeInfo(nodeid);

		List<Map<String, Object>> chnodelist = new ArrayList<Map<String, Object>>();
		if (Long.parseLong(cnmap.get("parentId").toString()) == 0) {
			chnodelist = webService.queryNodeBypid(cnmap.get("id"));
			if (chnodelist.size() > 0) {
				currentNode = chnodelist.get(0);
			}
			currentMenu = cnmap;
		} else {
			chnodelist = webService.queryNodeBypid(cnmap.get("parentId"));
			currentNode = cnmap;
			currentMenu = webService.queryNodeInfo(cnmap.get("parentId"));
		}

		mov.addObject("currentMenu", currentMenu);
		mov.addObject("currentNode", currentNode);
		mov.addObject("chlist", chnodelist);
		mov.addObject("cnodeid", nodeid);

		return mov;
	}

	@RequestMapping(value = "/read")
	public @ResponseBody Map<String, Object> read(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_SUCCESS);
		createParameterMap(request);
		try {
			boolean flag = webService.addClickInfo(paramsMap);
			if (!flag) {
				resultMap.put("msg", "修改失败!");
			} else {
				resultMap.put("error", "获取栏目数异常");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("error", "获取栏目数异常");
		}
		return resultMap;
	}

	@RequestMapping(value = "/loadpic")
	public @ResponseBody Map<String, Object> loadpic(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_SUCCESS);
		createParameterMap(request);
		///加载轮播图信息
		List<Map<String, Object>> alist = webService.queryTopArticle();
		resultMap.put("alist", alist);
		return resultMap;
	}

	@RequestMapping(value = "/company")
	public @ResponseBody Map<String, Object> companyDeail(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("ajax_status", AjaxStatusConstant.AJAX_STATUS_SUCCESS);
		createParameterMap(request);
		PageObject obj = siteCompanyService.querySiteCompanyList(resultMap);
		resultMap.put("obj", obj);
		return resultMap;
	}

	public String checkMoth(String str) {
		if (str.equals("01")) {
			return "JAN";
		}
		if (str.equals("02")) {
			return "FEB";
		}
		if (str.equals("03")) {
			return "MAR";
		}
		if (str.equals("04")) {
			return "APR";
		}
		if (str.equals("05")) {
			return "MAY";
		}
		if (str.equals("06")) {
			return "JUN";
		}
		if (str.equals("07")) {
			return "JUL";
		}
		if (str.equals("08")) {
			return "AUG";
		}
		if (str.equals("09")) {
			return "SEP";
		}
		if (str.equals("10")) {
			return "OCT";
		}
		if (str.equals("11")) {
			return "NOV";
		}
		if (str.equals("12")) {
			return "DEC";
		}
		return "";
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：跳转添加用户信息
	 * 创建人： ln
	 * 创建时间： 2016年11月30日
	 * 标记：PC
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toAddUserIndex")
	public ModelAndView toAddUserIndex(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mov = new ModelAndView();
		createParameterMap(request);
		//加载顶部menu动态部分
		List<Map<String, Object>> mlist = webService.queryFirstMenu();
		mov.addObject("mlist", mlist);
		mov.setViewName("/wap/skillsharing");
		return mov;
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：H5跳转添加用户信息
	 * 创建人： ln
	 * 创建时间： 2016年11月30日
	 * 标记：wap
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toAddUserIndexH5")
	public ModelAndView toAddUserIndexH5(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		ModelAndView mov = new ModelAndView();
		mov.setViewName("/wap/jinengH5");
		return mov;
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：添加用户信息
	 * 创建人： ln
	 * 创建时间： 2016年11月30日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/addUserIndex")
	public @ResponseBody Map<String, Object> addUserIndex(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			boolean flag = webService.addUserIndex(paramsMap);
			map.put("flag", flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：验证用户
	 * 创建人： ln
	 * 创建时间： 2016年12月2日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/checkUser")
	public @ResponseBody Map<String, Object> checkUser(HttpServletRequest request, HttpServletResponse response) {
		createParameterMap(request);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			boolean flag = webService.checkUser(paramsMap);
			map.put("checkFlag", flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * ajax方式获取js签名
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getJSConfig")
	public String getJSConfig(HttpServletRequest request, String clientUrl, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String resStr = null;
		try {
			String cUrl = clientUrl;
			cUrl = URLEncoder.encode(cUrl, "UTF-8");
			log.info("++++++++++++++++cUrl:" + cUrl);
			//String url = constants.getXiaoka_weixin_xydk_toGetJsConfig(); //暂时注释签名
			String url = null;
			log.info("=================clientUrl=================" + clientUrl);
			resultMap = HttpClientUtil.requestByGetMethod(url + "?clientUrl=" + cUrl);
			log.info("<<<<<<<<<<<clientUrl=================" + clientUrl);
			resStr = (String) resultMap.get("token");
		} catch (Exception e) {
			e.printStackTrace();
			log.info("<<<<<<<<<<<ajax方式获取js签名失败<<<<<<<<<<<<");
			resultMap.put("msg", "0");
			return resStr;
		}
		return resStr;
	}

	/**
	 * 微信分享入口
	 * @param session
	 * @param shareUrl 被分享页面的url
	 * @return
	 * @throws IllegalArgumentException
	 */
	@RequestMapping(value = "/wxShare")
	public String wxShare(final HttpServletRequest req, String shareUrl) {
		return "redirect:" + shareUrl;
	}

	/**
	 * 获取js签名
	 */
	/*@ResponseBody
	@RequestMapping(value = "/getJSConfig")
	public Object getJSConfig(String clientUrl) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String resStr = null;
		try{
			String url = constants.getXiaoka_weixin_xydk_toGetJsConfig();
			String ecodUrl = URLEncoder.encode(clientUrl,"UTF-8");
			resultMap = HttpClientUtil.requestByGetMethod(url+"?clientUrl="+ecodUrl);
			resStr = (String) resultMap.get("token");
		}catch(Exception e){
			e.printStackTrace();
			//log.info("<<<<<<<<<<<ajax方式获取js签名失败<<<<<<<<<<<<");
			resultMap.put("msg","0");
			return resStr;
		}
		return resStr;
	}*/

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：新闻列表，用于手机端入口。H5
	 * 创建人： ln
	 * 创建时间： 2017年1月6日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/toNewsList")
	public ModelAndView toNewsList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mov = new ModelAndView();
		mov.setViewName("/wap/news/newlist");
		return mov;
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：新闻列表，用于手机端入口。H5
	 * 创建人： ln
	 * 创建时间： 2017年1月6日
	 * 标记：
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/newsList")
	public @ResponseBody Map<String, Object> newsList(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		createParameterMap(request);
		try {
			paramsMap.put("limit", 10);
			PageObject po = webService.queryNewsList(paramsMap);
			/*List<Map<String,Object>> listTop = webService.queryNewListTop(paramsMap);*/
			List<Map<String, Object>> datasource = po.getDatasource();

			for (int i = 0; i < datasource.size(); i++) {
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateString = formatter.format(datasource.get(i).get("pubTime"));
				datasource.get(i).put("pubTime", dateString);
			}
			map.put("list", po.getDatasource());
			map.put("currentPage", po.getCurrentPage());
			/*map.put("listTop", listTop);*/
			String imgPreUrl = constants.getSftz_online_path();
			map.put("imgPreUrl", imgPreUrl);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 项目名称：sftj-offical-site
	 * 描述：更新阅读人数H5
	 * 创建人： ln
	 * 创建时间： 2017年1月6日
	 * 标记：WAP
	 * @param request
	 * @param response
	 * @return
	 * @version
	 */
	@RequestMapping(value = "/updateReadNum")
	public @ResponseBody Map<String, Object> updateReadNum(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		createParameterMap(request);
		try {
			webService.updateReadNum(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

}
